//
//  CHSVoiceRecorder.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-11-8.
//
//

#import "CHSVoiceRecorder.h"
#import "CHSVoiceHUD.h"
#import <AVFoundation/AVFoundation.h>
#import "MicroDef.h"
#import "ISTThemeLabel.h"
#import "ChatToolBar.h"

#pragma mark - <DEFINES>

#define WAVE_UPDATE_FREQUENCY   0.05

#pragma mark - <CLASS> CHSVoiceRecorder

@interface CHSVoiceRecorder () <AVAudioRecorderDelegate>
{
    NSTimer         *_timer;
    
    CHSVoiceHUD     *_voiceHud;
    
    BOOL            _isRecording;
    
    BOOL            _canUpdateImage;
}

@property(nonatomic,retain) AVAudioRecorder * recorder;

@end

@implementation CHSVoiceRecorder

-(void) dealloc
{
    if (self.recorder.isRecording) {
        [self.recorder stop];
    }
}

- (instancetype)init
{
    self = [super init];
    if (self) {
//        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//        
//        NSError *err = nil;
//        
//        [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
//        
//        if(err){
//            
//        } else {
//            
//            [audioSession setActive:YES error:&err];
//        }
        
    }
    return self;
}

- (void)setupRecorder
{
    
}

-(BOOL) isRecording
{
    return _isRecording;
}

-(void) startRecordWithPath:(NSString *)path
{
    _isRecording = YES;
    _canUpdateImage = NO;
    [self showVoiceHudWithStatus:CHSVoiceHUDStatusPrepare];
    
    NSError * err = nil;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
	[audioSession setCategory :AVAudioSessionCategoryRecord error:&err];

	if(err){
//        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
	}
    
    [audioSession setActive:YES error:&err];
    
    err = nil;
    
	if(err){
//        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
	}
    
    
    NSMutableDictionary * recordSetting = [[NSMutableDictionary alloc] init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:8000] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    
    [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    self.recordPath = path;
    NSURL * url = [NSURL fileURLWithPath:self.recordPath];
	
	err = nil;
    
    if(self.recorder){[self.recorder stop];self.recorder = nil;}
    
   
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];

    if(!_recorder){
//        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
								   message: [err localizedDescription]
								  delegate: nil
						 cancelButtonTitle:@"OK"
						 otherButtonTitles:nil];
        [alert show];
        [self hideVoiceHud];
        return;
	}
    
    [_recorder setDelegate:self];
	[_recorder prepareToRecord];
	_recorder.meteringEnabled = YES;
    
    
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
	if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
								   message: @"Audio input hardware not available"
								  delegate: nil
						 cancelButtonTitle:@"OK"
						 otherButtonTitles:nil];
        [cantRecordAlert show];
        [self hideVoiceHud];
        return;
	}
    
    [_recorder recordForDuration:(NSTimeInterval) 60];
    
    self.recordTime = 0;
    [self resetTimer];
    
    [self showVoiceHudWithStatus:CHSVoiceHUDStatusRecording];
    _canUpdateImage = YES;
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:WAVE_UPDATE_FREQUENCY target:self selector:@selector(updateMeters:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

-(void) stopRecordWithCompletionBlock:(void (^)(NSInteger))completion
{
    _canUpdateImage = NO;
    [self hideVoiceHud];
    if (self.recorder.isRecording) {
        [self.recorder stop];
    }
    if (self.recordTime<1.0)
    {
        [self showVoiceHudWithStatus:CHSVoiceHUDStatusShortTime];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self hideVoiceHud];
            
        });
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            completion((NSInteger)self.recordTime);
        });
    }
    [self resetTimer];
    
    _isRecording = NO;
}

-(void) recording
{
    [self showVoiceHudWithStatus:CHSVoiceHUDStatusRecording];
    _canUpdateImage = YES;
}

-(void) cancelled
{
    _canUpdateImage = NO;
    [self showVoiceHudWithStatus:CHSVoiceHUDStatusCancel];
}

-(void) finishCancelled
{
    [self.recorder stop];
//    if ([_recorder deleteRecording]) {
//        NSLog(@"删除成功！");
//    }
    _canUpdateImage = NO;
    [self hideVoiceHud];
    [self resetTimer];
    _isRecording = NO;
}

#pragma mark - Timer Update

- (void)updateMeters:(id)sender
{
    if (!_canUpdateImage) {
        return;
    }
    
    self.recordTime += WAVE_UPDATE_FREQUENCY;
    
       if (_voiceHud)
    {
        if (_recorder) {
            [_recorder updateMeters];
        }
        
    
        if ((NSInteger)self.recordTime >= 50 && (NSInteger)self.recordTime <= 60) {
            [_voiceHud setCountDownTime:60 - (NSInteger)self.recordTime];
            if ((NSInteger)self.recordTime == 60) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [[ChatToolBar defaultChatToolBar] btnUpInside:nil];
                });
            }
            return;
        }
        float peakPower = [_recorder peakPowerForChannel:0];
        double ALPHA = 0.05;
        double peakPowerForChannel = pow(10, (ALPHA * peakPower));
        [_voiceHud setProgress:peakPowerForChannel];
    }
}

-(void) cancelRecording
{
    if (self.recorder.isRecording) {
        [self.recorder stop];
    }
    
    self.recorder = nil;
}

-(void) showVoiceHudWithStatus:(CHSVoiceHUDStatus)status
{
    if (!_voiceHud) {
        _voiceHud = [[CHSVoiceHUD alloc] init];
    }
    [_voiceHud showWithStatus:status];
}

-(void) hideVoiceHud
{
    if (_voiceHud) {
        [_voiceHud hide];
    }
}

-(void) resetTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

@end
